package com.example.guarding_jc;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TosendDataSource {
	private SQLiteDatabase database;
	private TosendDatabaseHelper dbHelper;
	
	private String[] allColumns = {TosendTable.COLUMN_ID, TosendTable.COLUMN_SEQ, TosendTable.COLUMN_CHALLENGE,
			TosendTable.COLUMN_MAC, TosendTable.COLUMN_UID, TosendTable.COLUMN_TIME};
	
	public TosendDataSource(Context context){
		dbHelper = new TosendDatabaseHelper(context);
	}
	
	public void open() throws SQLException {
	    database = dbHelper.getWritableDatabase();
	}
	
	public void close(){
	    dbHelper.close();
	}
	
	public void createEntry(String seq, String challenge, String MAC, String uid, String time, String imei){
		ContentValues values = new ContentValues();
		values.put(TosendTable.COLUMN_SEQ, seq);
		values.put(TosendTable.COLUMN_CHALLENGE, challenge);
		values.put(TosendTable.COLUMN_MAC, MAC);
		values.put(TosendTable.COLUMN_UID, uid);
		values.put(TosendTable.COLUMN_TIME, time);
		values.put(TosendTable.COLUMN_IMEI, imei);
		
		long insertedID = database.insert(TosendTable.TABLE_TOSEND, null, values);
		Cursor cursor = database.query(TosendTable.TABLE_TOSEND, allColumns, TosendTable.COLUMN_ID + " = " + insertedID, null, null, null, null);
		cursor.moveToFirst();
		cursor.close();
	}
	
	public void deleteEntry(String entryId){
		database.delete(TosendTable.TABLE_TOSEND, "_id = " + entryId, null);
	}
	
	public List<DBEntry> getAllPendingScans(){
		List<DBEntry> entries = new ArrayList<DBEntry>();
		Cursor cursor = database.query(TosendTable.TABLE_TOSEND, null, null, null, null, null, null, null);
		cursor.moveToFirst();
		
		while(!cursor.isAfterLast()){
			DBEntry entry = cursorToEntry(cursor);
			Log.i("Entry: ", entry.toString());
			entries.add(entry);
			cursor.moveToNext();
		}
		
		cursor.close();
		
		return entries;
	}
	
	private DBEntry cursorToEntry(Cursor cursor){
		DBEntry entry = new DBEntry();
		entry.setId(cursor.getString(0));
		entry.setSeq(cursor.getString(1));
		entry.setChallenge(cursor.getString(2));
		entry.setMac(cursor.getString(3));
		entry.setUid(cursor.getString(4));
		entry.setTime(cursor.getString(5));
		entry.setImei(cursor.getString(6));
		return entry;
	}
}
